package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.service.IStrategyService;
import cn.wolfcode.trip.base.util.UploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author by mycp
 * @Classname StrategyController
 * @Description TODO 攻略文章处理器
 * @Date 2018/11/7 22:05
 */
@Controller
@RequestMapping("/strategyDetail")
public class StrategyDetailController {
    @Autowired
    private IStrategyDetailService strategyDetailService;

    @Autowired
    private IStrategyService strategyService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model){
        // 根据攻略的发布时间进行倒序查询, 最近更新的游记显示在最前面
        qo.setOrderBy("sd.releaseTime desc");
        PageInfo pageInfo = strategyDetailService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        // 查询所有不被禁用的攻略
        model.addAttribute("strategies", strategyService.selectEnable());
        return "strategyDetail/list";
    }

    /**
     * 保存 / 新增攻略文章
     * @param strategyDetail
     * @param img
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(StrategyDetail strategyDetail, MultipartFile img){
        // 先判断前台是否有上传图片 且文件是否是图片格式
        // 定义文件上传文件的格式后缀名
        String fileType = "image";
        if (img != null && img.getContentType().startsWith(fileType)){
            // 先保存更新后的封面
            String coverUrl = UploadUtil.upload(img);
            // 将更改后的封面的url设置到strategy中替换掉旧的封面
            strategyDetail.setCoverUrl(coverUrl);
        }
        strategyDetailService.saveOrUpdate(strategyDetail);
        return  "redirect:/strategyDetail/list.do";
    }

    /**
     * 根据攻略文章 id 获取文章内容
     * @param id
     * @return
     */
    @RequestMapping("/getContent")
    @ResponseBody
    public Object getContentById(Long id){
        return strategyDetailService.getContentById(id);
    }
}
